package com.zbb.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zbb.base.execption.ZbbBackException;
import com.zbb.base.model.Result;
import com.zbb.user.mapper.CreditMapper;
import com.zbb.user.mapper.UserMapper;
import com.zbb.user.model.dto.UserLoginDto;
import com.zbb.user.model.dto.UserRegisterFrom;
import com.zbb.user.model.po.Credit;
import com.zbb.user.model.po.User;
import com.zbb.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author itcast
 */
@Service
public class UserRegisterServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    CreditMapper creditMapper;

    @Override
    public User queryUserInfo(String userId) {
        User user = userMapper.selectById(userId);
        Credit credit = creditMapper.selectNewCredit(userId);
        if (credit != null) {
            user.setCreditScore(credit.getCreditScore());
        }else {
            user.setCreditScore(5.0F);
        }
        return user;
    }

    /**
     * 注册接口
     *
     * @param userRegisterFrom
     * @return
     */
    @Override
    public Result register(UserRegisterFrom userRegisterFrom) {
        //判断数据库中是否存在
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("student_id",userRegisterFrom.getStudentId());
        User user1 = userMapper.selectOne(userQueryWrapper);
        if (user1 != null){
            throw new ZbbBackException("该学号已存在,若不是本人操作，请联系管理员。");
        }
        QueryWrapper<User> userQueryWrapper1 = new QueryWrapper<>();
        userQueryWrapper1.eq("phone_no",userRegisterFrom.getPhoneNo());
        User user2 = userMapper.selectOne(userQueryWrapper);
        if (user2 != null){
            throw new ZbbBackException("该手机号已存在,若不是本人操作，请联系管理员。");
        }
        QueryWrapper<User> userQueryWrapper2 = new QueryWrapper<>();
        userQueryWrapper2.eq("user_name",userRegisterFrom.getUserName());
        User user3 = userMapper.selectOne(userQueryWrapper2);
        if (user3 != null){
            throw new ZbbBackException("该用户名已存在，请输入其他用户名");
        }
        User user = new User();
        user.setUserName(userRegisterFrom.getUserName());
        user.setStudentName(userRegisterFrom.getStudentName());
        user.setPhoneNo(userRegisterFrom.getPhoneNo());
        user.setSchoolId(userRegisterFrom.getSchoolId());
        user.setCampusId(userRegisterFrom.getCampusId());
        user.setStudentId(userRegisterFrom.getStudentId());
        String uuid = UUID.randomUUID().toString();
        user.setId(uuid);
        LocalDateTime time = LocalDateTime.now();
        user.setRegisterTime(time);
        user.setUpdateTime(time);
        user.setLoginTime(time);
//        密码加密存储
        //MD5加密可以被暴力破解
        //加盐
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String s = passwordEncoder.encode(userRegisterFrom.getPassword());
        user.setPassword(s);

        user.setPhotoUrl("https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg");
        user.setCreditScore(5f);
        int insert = userMapper.insert(user);
        if (insert == 1){
            return Result.ok("注册成功");
        }
        return Result.fail("注册失败");
    }

    @Override
    public User login(UserLoginDto userLoginDto) {
        String studentId = userLoginDto.getStudentId();
        String password = userLoginDto.getPassword();
        //1查询用户数据库
        User user = userMapper.selectOne(new QueryWrapper<User>()
                .eq("student_id",studentId)
                .or().eq("phone_no", studentId));
        if (user == null){
            //登录失败
            return null;
        } else {
            String passwordDB = user.getPassword();
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            boolean matches = bCryptPasswordEncoder.matches(password, passwordDB);
            if (matches){
                LocalDateTime time = LocalDateTime.now();
                user.setLoginTime(time);
                userMapper.insert(user);
                return user;
            }else {
                return null;
            }
        }
    }

    @Override
    public User updateUser(User user) {
        User user1 = userMapper.selectById(user.getId());
        if (user.getUserName()!=null){
            user1.setUserName(user.getUserName());
        }
        if (user.getStudentId()!=null){
            user1.setStudentId(user.getStudentId());
        }
        if (user.getUserName()!=null){
            user1.setStudentName(user.getStudentName());
        }
        if (user.getPhoneNo()!=null){
            user1.setPhoneNo(user.getPhoneNo());
        }
        if (user.getPhotoUrl()!=null){
            user1.setPhotoUrl(user.getPhotoUrl());
        }
        if (user.getPersonalSignature()!=null){
            user1.setPersonalSignature(user.getPersonalSignature());
        }
        user1.setUpdateTime(LocalDateTime.now());
        userMapper.updateById(user1);
        return user1;
    }


}
